#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <fcntl.h>

#define	DEBUG

#define	MAX_BACKLOG	32
#define	REQ_BUF_LEN	32
#define	HDR_BUF_LEN	20

void *client_process(void *arg);

int main(int argc, char *argv[])
{
	int ret;
	int listenfd;
	int opt = 1;
	int connfd;
	int *tempfd;
	struct sockaddr_in servaddr;
	struct sockaddr_in cliaddr;
	socklen_t addrlen;
	unsigned short port;

	if (argc != 2) {
		printf("Usage: %s port\n", argv[1]);
		exit(EXIT_FAILURE);
	}

	listenfd = socket(AF_INET, SOCK_STREAM, 0);
	if (listenfd == -1) {
		perror("server->socket");
		exit(EXIT_FAILURE);
	}
	setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));

	memset(&servaddr, 0, sizeof(struct sockaddr_in));
	port = atoi(argv[1]);
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

	ret = bind(listenfd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr_in));
	if (ret == -1) {
		perror("server->bind");
		close(listenfd);
		exit(EXIT_FAILURE);
	}

	ret = listen(listenfd, MAX_BACKLOG);
	if (ret == -1) {
		perror("server->listen");
		close(listenfd);
		exit(EXIT_FAILURE);
	}

		addrlen = sizeof(struct sockaddr_in);
		memset(&cliaddr, 0, sizeof(struct sockaddr_in));
		connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &addrlen);
		if (connfd == -1) {
			perror("server->accept");
			//continue;
		}
#ifdef DEBUG
		printf("server->accept: a new client is comming, and the connfd is %d\n", connfd);
#endif

	int si_fd=open("/dev/ttyUSB0",O_RDWD);

	char buf[36]={0};
		memset(buf,0,sizeof(buf));
	int n=serial_recv_exact_nbytes(si_fd,buf,sizeof(buf));
		if(n==sizeof(buf))
			int wfd=write(connfd,buf,sizeof(buf));
				if(wfd!=sizeof(buf))
					perror("Socket Write error");
		memset(buf,0,sizeof(buf));
		
}

void *client_process(void *arg)
{

	int connfd;
	connfd = *(int *)arg;
	
	/*与客户端处理的业务逻辑*/
	pthread_exit(NULL);
}
